from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
# MongoDB连接配置
MONGO_HOST = "101.227.69.34"
MONGO_PORT = 2929
MONGO_USER = "admin"
MONGO_PASS = "admin"
DB_NAME = "my_database"  # 添加要创建的数据库名称
try:
    # 创建MongoDB客户端连接
    client = MongoClient(
        host=MONGO_HOST,
        port=MONGO_PORT,
        username=MONGO_USER,
        password=MONGO_PASS,
        authSource="admin"
    )
    # 测试连接
    client.admin.command("ping")
    print("MongoDB连接成功！")
    # 创建/获取数据库 (MongoDB会在第一次插入数据时真正创建数据库)
    db = client[DB_NAME]
    # 创建一个集合并插入一条测试数据
    test_collection = db["test_collection"]
    test_collection.insert_one({"message": "数据库创建测试"})
    print(f"数据库 '{DB_NAME}' 创建成功，并已添加测试数据")
    print(f"当前数据库列表: {client.list_database_names()}")
except ConnectionFailure as e:
    print(f"MongoDB连接失败: {e}")
except Exception as e:
    print(f"发生错误: {e}")
finally:
    # 关闭连接
    if "client" in locals():
        client.close()